package com.vincent.sciinfo.controller;

import com.alibaba.fastjson.JSON;
import com.vincent.sciinfo.pojo.TSMResult;
import com.vincent.sciinfo.pojo.Teacher;
import com.vincent.sciinfo.pojo.UpdatePasswordDto;
import com.vincent.sciinfo.pojo.User;
import com.vincent.sciinfo.service.LoginCountService;
import com.vincent.sciinfo.service.SourceService;
import com.vincent.sciinfo.service.TeacherService;
import com.vincent.sciinfo.service.UserService;
import com.vincent.sciinfo.utils.FilePathUtils;
import com.vincent.sciinfo.utils.JwtUtils;
import com.vincent.sciinfo.utils.StatusCode;
import com.vincent.sciinfo.utils.StatusMessage;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userServer;

    @Autowired
    private TeacherService teacherServer;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private LoginCountService loginCountServer;

    @Autowired
    private SourceService sourceServer;

    //未被注销的用户 以及非教师用户
    public void loginOperation(User user, Map map, TSMResult tsmResult) {
        //否则没有注销
        String jwt = jwtUtils.generateToken(user.getUserId());
        map.put("token", jwt);
        user = userServer.getUserById(user);
        //登录即登录次数加一
        loginCountServer.checkUserCountNum(user);
        tsmResult.setMessage(StatusMessage.SUCCESS);
        tsmResult.setCode(StatusCode.SUCCESS);
        user.setUserPaswd("已加密...");
        tsmResult.setData(user);
        map.put("tsmResult", tsmResult);
    }

    //登录
    @RequestMapping("/login")
    public Map checkLogin(@RequestBody(required = false) User user) {
        Map<String, Object> map = new HashMap<>();
        TSMResult tsmResult = new TSMResult();
        String inputId = user.getUserId();
        String inputPaswd = user.getUserPaswd();

        boolean flag = userServer.checkUser(inputId);
        if (!flag) {
            tsmResult.setCode(StatusCode.NOT_FOUND);
            tsmResult.setMessage(StatusMessage.USER_NOT_FOUND);
            map.put("tsmResult", tsmResult);
        } else {
            String paswd = userServer.getUserById(user).getUserPaswd();
            if (!paswd.equals(inputPaswd)) {
                tsmResult.setCode(StatusCode.FAILED);
                tsmResult.setMessage(StatusMessage.WRONG_LOGIN_INFO);
                tsmResult.setData(0);
                map.put("tsmResult", tsmResult);
            } else {
                //如果存在 并且密码没错误 但是如果该用户是教师 并且该教师已被注销
                // 应该叫教师去联系管理员
                TSMResult teacherTSMResult = teacherServer.getTeacherInfor(new TSMResult(), user.getUserId());

                //将TSMResult通用类的data 转换为具体对象
                Teacher teacher = JSON.parseObject(JSON.toJSONString(teacherTSMResult.getData()), Teacher.class);

                //如果是教师
                if (teacher != null) {
                    Integer teacherStatus = teacher.getTeacherstatu();
                    if (teacherStatus == 2) {
                        tsmResult.setCode(StatusCode.FAILED);
                        tsmResult.setMessage(StatusMessage.USER_LOG_OUT);
                        tsmResult.setData(teacherStatus);
                        map.put("tsmResult", tsmResult);
                        return map;
                    } else {
                        this.loginOperation(user, map, tsmResult);
                    }
                } else {
                    this.loginOperation(user, map, tsmResult);
                }
            }
        }
        return map;
    }

    //更改密码 password 改为 newPassword
    @RequestMapping("/updatePassword")
    public TSMResult updatePassword(@RequestBody(required = false) UpdatePasswordDto updatePasswordDto, TSMResult tsmResult) {
        String username = updatePasswordDto.getUsername();
        String password = updatePasswordDto.getNewPassword();
        int result = userServer.updatePassword(username, password);
        tsmResult.setData(result);
        tsmResult.setCode(StatusCode.SUCCESS);
        tsmResult.setMessage(StatusMessage.UPDATEPWD_SUCCESS);
        return tsmResult;
    }

    //下载论文
    @RequestMapping(value = "/DownloadServlet")
    public ResponseEntity<byte[]> fileDownload(
            HttpServletRequest request,
            @RequestParam("paperName") String fileName) throws Exception {
        //fileName = new String(fileName.getBytes("ISO-8859-1"), "UTF-8"); //后台接受中文数据编码
        fileName = fileName + ".doc";

        //String filePath = request.getServletContext().getRealPath("./") + File.separator + UPLOAD_DIRECTORY + "\\" + fileName;
        String filePath = FilePathUtils.getFileUploadPath() + fileName;
        File file = new File(filePath);

        HttpHeaders headers = new HttpHeaders();
        String downloadFile = new String(fileName.getBytes("utf-8"), "iso-8859-1");
        headers.setContentDispositionFormData("attachment", downloadFile);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
    }

    //elementUI 上传方法
    @PostMapping(value = "/uploading")
    public TSMResult uploadFile(
            @RequestParam("file") MultipartFile file,
            TSMResult tsmResult) {
        //上传文件的路径
        String filePath = FilePathUtils.getFileUploadPath();
        //filename 包括文件的后缀名
        String filename = file.getOriginalFilename();

        TSMResult fileTsmResult = sourceServer.isExistsFilename(filename);

        //JSON从JSONString中解析对象
        //其中利用JSON.toJSONString 将fileTsmResult.getData() 转换成JSONString
        //然后从转换后的JSONString 解析成Source对象
        Boolean isExists = JSON.parseObject(JSON.toJSONString(fileTsmResult.getData()), Boolean.class);
        if (isExists) {
            tsmResult.setData(0);
            tsmResult.setMessage(StatusMessage.FILE_EXISTED);
            return tsmResult;
        }

        //用来判断上传文件的父目录是否存在
        File fileTestDirIFExists = new File(filePath);
        if (!fileTestDirIFExists.exists()) {
            //如果目录不存在 则手动创建一个新目录
            //mkdirs 可以在C盘下 创建多个连续的子目录
            fileTestDirIFExists.mkdirs();
        }

        //真正存储的目标文件
        File dest = new File(filePath + filename);
        try {
            //开始从web上传的file 存储到目标file
            file.transferTo(dest);

            //数据库中存储文件的路径
            sourceServer.saveFilePath(filePath, filename);
            tsmResult.setData(1);
            tsmResult.setMessage(StatusMessage.FILE_UPLOAD_SUCCESS);
            return tsmResult;
        } catch (IOException e) {
            e.printStackTrace();
            tsmResult.setData(0);
            tsmResult.setMessage(StatusMessage.FILE_UPLOAD_FAILED);
        }
        return tsmResult;
    }


    @RequestMapping("/insertUser")
    public int insertUser(@RequestBody Teacher teacher) {
        User user = new User();
        user.setUserId(teacher.getTeacherid());
        user.setUserPaswd(teacher.getTeacherid());
        user.setUserType(3);
        return userServer.insert(user);
    }

    //查询所有会议
//    @RequestMapping("/show_meeting")
//    @ResponseBody
//    public Map showAllTheMeeting() {
//        List<Meeting> list = meetingServer.selectAllMeeting();
//        Map<String, Object> map = new HashMap<>();
//        List<Meeting> meetingList = new ArrayList<>();  //大的List
//        //根据每一个会议编号 去查询对应的人员
//        for (Meeting meeting : list) {
//            //查出来的是多个数据
//            List<TakeMeeting> takeMeetingList = teacherServer.selectByMeetingId(meeting.getMeetingid()); //列中的List
//            meeting.setTakeMeetingList(takeMeetingList);
//            meetingList.add(meeting);
//        }
//        map.put("meetingList", meetingList);
//        map.put("tsmResult", new TSMResult(200, "查询成功", list));
//        return map;
//    }
}
